import com.drew.imaging.ImageProcessingException;
import org.apache.commons.imaging.ImageReadException;
import org.apache.commons.imaging.ImageWriteException;
import org.apache.commons.imaging.Imaging;
import org.apache.commons.imaging.common.ImageMetadata;
import org.apache.commons.imaging.formats.jpeg.JpegImageMetadata;
import org.apache.commons.imaging.formats.jpeg.exif.ExifRewriter;
import org.apache.commons.imaging.formats.tiff.TiffImageMetadata;
import org.apache.commons.imaging.formats.tiff.constants.ExifTagConstants;
import org.apache.commons.imaging.formats.tiff.write.TiffOutputDirectory;
import org.apache.commons.imaging.formats.tiff.write.TiffOutputSet;

import com.drew.imaging.ImageMetadataReader;
import com.drew.metadata.Metadata;
import com.drew.metadata.exif.ExifSubIFDDirectory;

import javax.imageio.*;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.metadata.IIOMetadataNode;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import java.io.File;
import java.io.IOException;
import java.util.Date;

import com.drew.imaging.ImageMetadataReader;
import com.drew.imaging.ImageProcessingException;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.exif.ExifIFD0Directory;
import com.drew.metadata.exif.ExifSubIFDDirectory;
import com.drew.metadata.exif.makernotes.NikonType2MakernoteDirectory;
import com.drew.metadata.exif.ExifDirectoryBase;

public class PhotoUtils {

    public static void main(String[] args) {
        File file = new File("E:\\陈婉霞\\cs\\IMG_20180612_220413 - 副本.jpg");
        //getTagDateTimeOriginal(file);
        //setNewDateTime(file, null);
        File imageFile = new File("E:\\陈婉霞\\cs\\IMG_20180612_220413 - 副本.jpg");

        try {
            Metadata metadata = ImageMetadataReader.readMetadata(imageFile);
            ExifSubIFDDirectory subIfdDirectory = metadata.getFirstDirectoryOfType(ExifSubIFDDirectory.class);

            if (subIfdDirectory != null) {
                Date newDate = new Date(); // 设置新的拍摄时间，这里使用当前时间作为示例

                // 修改拍摄时间信息
                subIfdDirectory.setDate(ExifDirectoryBase.TAG_DATETIME_ORIGINAL, newDate);
                subIfdDirectory.setDate(ExifDirectoryBase.TAG_DATETIME_DIGITIZED, newDate);

                // 更新其他相关的拍摄时间信息（可选）
                ExifIFD0Directory ifd0Directory = metadata.getFirstDirectoryOfType(ExifIFD0Directory.class);
                if (ifd0Directory != null) {
                    ifd0Directory.setDate(ExifDirectoryBase.TAG_DATETIME, newDate);
                }

                // 保存修改后的元数据到照片文件中（这里使用其他库或方法来实现）
                // TODO: 保存修改后的元数据到照片文件中

                System.out.println("拍摄时间已成功修改为: " + newDate);
            } else {
                System.out.println("未找到拍摄时间信息。");
            }
        } catch (ImageProcessingException | IOException e) {
            System.out.println("修改拍摄时间失败: " + e.getMessage());
        }
    }

    public static void changeFileName(File folder, File file) {
        // 指定要修改的文件夹路径
        //String folderPath = "E:\\陈婉霞\\视频";
        // 创建 File 对象，表示文件夹
        //File folder = new File(folderPath);
        // 检查文件夹是否存在
        try {
            // 获取文件名
            String fileName = file.getName();
            if (!Main.effectiveYear.contains(fileName)) {
                // 创建正则表达式匹配模式
                Pattern pattern = Pattern.compile("\\d+");
                // 创建 Matcher 对象，并将字符串与正则表达式匹配
                Matcher matcher = pattern.matcher(fileName);
                // 遍历匹配结果
                String timeStampStr = "";
                while (matcher.find()) {
                    // 获取匹配到的数字部分
                    timeStampStr += matcher.group();
                }
                // 创建 Date 对象，并传入时间戳
                Long timeStamp = timeStampStr.length() == 14 ? Long.parseLong(timeStampStr) / 10 : Long.parseLong(timeStampStr);
                Date date = new Date(timeStamp);
                // 输出日期
                SimpleDateFormat sdfYear = new SimpleDateFormat("yyyy");
                SimpleDateFormat sdfTime = new SimpleDateFormat("yyyyMMddHHmmss");
                String year = sdfYear.format(date);
                String dateFileName = sdfTime.format(date);
                if (Main.effectiveYear.contains(year)) {
                    System.out.println(dateFileName);
                    // 修改文件名
                    String newFileName = dateFileName + "-" + fileName;
                    // 创建新的 File 对象，指向修改后的文件路径
                    File newFile = new File(folder, newFileName);
                    // 执行文件重命名操作
                    boolean renamed = file.renameTo(newFile);
                    if (renamed) {
                        System.out.println("文件名修改成功：" + fileName + " -> " + newFileName);
                    } else {
                        System.out.println("文件名修改失败：" + fileName);
                    }
                } else {
                    System.out.println("文件名不是时间戳");
                }
            }
        } catch (Exception e) {
            e.getMessage();
        }
    }

    public static void checkTagDateTimeOriginal(File file, String targetUrl) {
        String sourceUrl = file.getPath();
        String fileName = file.getName();
        String date = PhotoUtils.getTagDateTimeOriginal(file);
        if (date != null) {
            FileUtils.moveFile(sourceUrl, targetUrl + "\\" + fileName);
        }
    }

    public static void setNewDateTime(File file, String targetUrl) {
        try {
            String fileName = file.getName();
            //获取ImageMetadata对象实例
            ImageMetadata metadata = Imaging.getMetadata(file);
            //强转为JpegImageMetadata
            JpegImageMetadata jpegMetadata = (JpegImageMetadata) metadata;
            //获取TiffImageMetadata
            TiffImageMetadata exif = jpegMetadata.getExif();
            //转换为流
            TiffOutputSet out = exif.getOutputSet();
            //获取TiffOutputDirectory
            TiffOutputDirectory exifDirectory = out.getOrCreateExifDirectory();
            //移除拍摄时间
            exifDirectory.removeField(ExifTagConstants.EXIF_TAG_DATE_TIME_ORIGINAL);
            exifDirectory.removeField(ExifTagConstants.EXIF_TAG_DATE_TIME_DIGITIZED);
            //初始化时间
            //String date = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss").format(new Date());
            String data = DateUtils.getTimeByFileName(file.getName(), "yyyy:MM:dd HH:mm:ss");
            System.out.println("文件名:" + file.getName() + ",拍摄时间:" + data);
            //添加拍摄时间 格式为"yyyy:MM:dd HH:mm:ss"
            exifDirectory.add(ExifTagConstants.EXIF_TAG_DATE_TIME_ORIGINAL, data);
            exifDirectory.add(ExifTagConstants.EXIF_TAG_DATE_TIME_DIGITIZED, data);
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(targetUrl + "\\" + fileName));
            //写入新的图片
            new ExifRewriter().updateExifMetadataLossless(file, bos, out);
            FileUtils.deleteFile(file);
        } catch (Exception e) {
            //很多图片可能读取exif出现异常为正常现象 通常无需处理
            e.printStackTrace();
        }
    }

    /**
     * 获取拍摄时间
     *
     * @param file
     */
    public static String getTagDateTimeOriginal(File file) {
        try {
            Metadata metadata = ImageMetadataReader.readMetadata(file);
            ExifSubIFDDirectory directory = metadata.getFirstDirectoryOfType(ExifSubIFDDirectory.class);
            if (directory != null) {
                Date date = directory.getDate(ExifSubIFDDirectory.TAG_DATETIME_ORIGINAL);
                if (date != null) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String formattedDate = sdf.format(date);
                    return formattedDate;
                } else {
                    System.out.println("拍摄日期不存在");
                }
            } else {
                System.out.println("照片中没有Exif信息");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ImageProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

}
